package com.java.admin.controller;

import com.java.admin.param.AdminUserParam;
import com.java.admin.pojo.AdminUser;
import com.java.admin.service.AdminUserService;
import com.java.param.PageParam;
import com.java.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
public class AdminUserController {
    @Autowired
    private AdminUserService adminUserService;

    @PostMapping("/user/login")
    public R login(@Validated AdminUserParam adminUserParam, BindingResult result, HttpSession session){
        if (result.hasErrors()) {
            return R.fail("参数异常，无法登录！");
        }
        //验证验证码
        String captcha = (String) session.getAttribute("captcha");
        if(!adminUserParam.getVerCode().equalsIgnoreCase(captcha)){
            R fail = R.fail("验证码输入错误！");
            fail.setCode("003");
            return fail;
        }
        //验证账号密码
        AdminUser adminUser = adminUserService.login(adminUserParam);
        if(adminUser==null){
            return R.fail("登录失败！账号或密码输入错误！");
        }
        session.setAttribute("userInfo",adminUser);
        return R.ok("登陆成功！");
    }

    @GetMapping("/user/logout")
    public R logout(HttpSession session){
        //清空登录session，包括登录后保存的数据
        //session.removeAttribute("userInfo");只清空key的数据
        session.invalidate();
        return R.ok("退出登录成功！");
    }

}
